package com.itany.corejava.code16_反射;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年08月12日11:19
 */
public class Test04_Field {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Class c=User.class;

        //1.获取当前类以及父类中所有public修饰的属性
        Field[] fields=c.getFields();
        System.out.println(Arrays.toString(fields));

        //2.获取当前类中的所有的属性，不区分修饰符
        Field[] delaredFields=c.getDeclaredFields();
        System.out.println(Arrays.toString(delaredFields));


        // 3.获取当前类以及其父类中指定的由public修饰的属性
        Field usernameField=c.getField("username");
        System.out.println(usernameField);
        //由于password被private修饰
        // Field passwordField=c.getField("password");
        // System.out.println(passwordField);

        //父类中的
        Field ageField=c.getField("age");
        System.out.println(ageField);

        // 4.获取当前类中指定的属性，不区分修饰符
        Field passwordField=c.getDeclaredField("password");
        System.out.println(passwordField);

        //无法获取父类属性，报错
       // Field nameField= c.getDeclaredField("name");
       //  System.out.println(nameField);

        User user=new User();
        usernameField.set(user,"admin");
        usernameField.set(user,"coco");

        //不能访问private修饰的属性
        // passwordField.set(user,"123");
        System.out.println(user);

        String username= (String) usernameField.get(user);
        System.out.println(username);

        //不能访问private修饰的属性
        // String password= (String) passwordField.get(user);
        // System.out.println(password);


        //设置取消权限控制检查, 访问忽略调用者的访问控制符
        passwordField.setAccessible(true);
        passwordField.set(user,"12345");
        System.out.println(user);
        String password= (String) passwordField.get(user);
        System.out.println(password);

    }
}
